<?php

namespace App\Http\Controllers;

use App\Helpers\Tools;
use App\Models\Works;
use App\Models\WorksZan;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Http\Resources\Works as WorksResource;

class UserController extends ApiController
{
    /**
     * 用户上传作品
     *
     * @param int $userId 用户id
     * @param string $wroksBase 用户作品base64码
     * @param string $content 用户作品文字内容
     * @param
     *
     * @return $response;
     *
     * @author long
     */
    public function createWorks()
    {
        $userId = request('userId', 1);
        if($userId == 'undefined') {
            $userId = 1;
        }
        $worksBase = request('worksBase');
        $content = request('content');

        $checkKey = 'works:user';

        // 验证该用户是否上传过作品
//        if (Redis::getbit($checkKey, $userId) == 1) {
//            return $this->response(Tools::error('您已经上传过作品了哦'));
//        }

        // 保存图片
        preg_match('/^(data:\s*image\/(\w+);base64,)/', $worksBase, $result);

        $type = $result[2];
        $fileName = $userId . time() . '.' . $type;
        $path = date('Y-m-d') . $fileName;
        $savePath = public_path() . '/uploads/' . $path;

        $res = file_put_contents($savePath, base64_decode(str_replace($result[1], '', $worksBase)));

        if ($res) {
            // 存储到数据库
            $works = new Works();

            $works->user_id = $userId;
            $works->content = $content;
            $works->works_url = $path;
            $works->user_sn = $this->worksSn();

            $res = $works->save();

            // 设置该用户已经上传过作品
            Redis::setbit($checkKey, $userId, 1);

            if ($res) {
                $response = new WorksResource($works);
                return $response;
            } else {
                return $this->response(Tools::error('上传失败'));
            }

        } else {
            return $this->response(Tools::error('图片保存失败'));
        }

    }

    /**
     * 用户点赞功能
     *
     * @param   int $userId 点赞的用户id
     * @param   int $worksId 作品id
     *
     * @return $response;
     *
     * @author long
     */
    public function zan()
    {
        $worksId = request('worksId');
        $userId = request('userId');
        $date = date('Ymd');
        $checkKey = "zan1:user:$userId";

        // 验证该用户今天是否赞过
        if (Redis::getbit($checkKey, $date)) {
            return $this->response(Tools::error('一天只能点赞一次哦！'));
        }

        try {
            $works = Works::find($worksId);
            $worksZan = new WorksZan();

            // 添加作品表点赞次数
            $works->support_count = $works->support_count + 1;

            // 添加点赞记录
            $worksZan->works_id = $worksId;
            $worksZan->zan_user_id = $userId;

            DB::beginTransaction();

            // 添加redis好判断他今天是否已经赞过
            Redis::setBit($checkKey, $date, 1);

            // 存储mysql数据
            $works->save();
            $worksZan->save();

            DB::commit();

        } catch (\Exception $e) {
            // 接收异常处理并回滚
            DB::rollBack();

            // 添加日志
            Tools::logError($e->getMessage());

            return $this->response(Tools::error('点赞失败，请重新点击'));
        }

        return $this->response(Tools::success('点赞成功'));

    }

    /**
     * 生成作品编号
     *
     * @return $sn;
     *
     * @author long
     */
    public function worksSn()
    {
        $checkKey = 'works:sn';
        Redis::incr($checkKey);
        $sn = Redis::get($checkKey);

        return $sn;
    }
}
















